import rpcCreator from './rpc.js'
import { OdooBus } from './rpc.js'

import { ModelClass } from './models'

// import addons from './addons'
// console.log('addons 1', addons)

const odooAddonsFiles = require.context('./addons', true, /\.js$/)

const addons = odooAddonsFiles.keys().reduce((models, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = odooAddonsFiles(modulePath)
  models[moduleName] = value.default
  return models
}, {})

// console.log('addons', odooAddons)

export class ODOO {
  constructor(params) {
    const { error } = params
    this.rpc = rpcCreator({ error })
    this.bus = OdooBus.getBus()
  }

  async login(params) {
    console.log(' ODOO,login,', params, this.rpc)

    return this.rpc.login(params)
  }

  async getInfo(token) {
    return this.rpc.getInfo(token)
  }

  async logout(params) {
    return this.rpc.logout(params)
  }

  async call(model, method, args, kwargs) {
    return this.rpc.call(model, method, args, kwargs)
  }

  // Not Used
  ref(xmlid) {
    // get model and id from xmlid
    return this.env('ir.model.data').call('xmlid_to_res_model_res_id', [
      xmlid,
      true
    ])
  }

  get_userinfo() {
    return this.rpc.get_userinfo()
  }

  env(model) {
    const model_addons = addons[model]
    const model_extend = model_addons && model_addons.extend
    const MyModelClass = model_extend ? model_extend(ModelClass) : ModelClass
    return new MyModelClass({ model, rpc: this.rpc, env: this.env })
  }
}

const odooCreator = ({ error }) => {
  return new ODOO({ error })
}

export default odooCreator
